package com.strawcom.charmring.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.android.volley.Request.Method;
import com.google.gson.JsonSyntaxException;
import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.UserInfo;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.bean.http.HeadImageResponse;
import com.strawcom.charmring.bluetooth.RingBleService;
import com.strawcom.charmring.util.*;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.view.CustomProgressDialog;
import com.strawcom.charmring.view.SelectDialog;
import com.strawcom.charmring.view.TitleView;
import com.strawcom.charmring.view.WheelView;
import com.strawcom.charmring.view.WheelView.OnWheelViewListener;
import com.strawcom.charmring.view.datetimepicker.DatePickerDialog;
import com.strawcom.charmring.view.datetimepicker.DatePickerDialog.OnDateSetListener;
import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.utils.SystemTool;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * @ClassName: UserInfoActivity
 * @Description:用户信息
 * @author liyongqiang
 * @date 2015-3-31 下午8:06:48
 * 
 */
public class UserInfoActivity extends BaseActivity implements OnClickListener, OnDateSetListener {

	private TitleView textView;
	private EditText editName;
	private TextView editweight, editHeight;
	private Button btnOk;
	private TextView tvBirthday, tvSex;
	private CustomProgressDialog dialog;
	private ImageView imgHead;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_userinfo);
		super.onCreate(savedInstanceState);
		initViews();

		findViewById(R.id.layout_content).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				closeInputMethod();
			}
		});

	}

	@SuppressLint("SimpleDateFormat") private void initViews() {
		textView = (TitleView) findViewById(R.id.title_view);
		textView.setTitleText(R.string.userinfo_title);

		editName = (EditText) findViewById(R.id.edit_name);
		tvBirthday = (TextView) findViewById(R.id.edit_birthday);
		tvSex = (TextView) findViewById(R.id.edit_sex);
		editweight = (TextView) findViewById(R.id.edit_weights);
		editweight.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				float currWeight = 0;
				String w = editweight.getText().toString();
				if (!TextUtils.isEmpty(w)) currWeight = Float.parseFloat(w);

				showModiWeightDialog(currWeight);
			}
		});
		editHeight = (TextView) findViewById(R.id.edit_heights);
		editHeight.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				int currHeight = 0;
				String h = editHeight.getText().toString();
				if (!TextUtils.isEmpty(h)) currHeight = Integer.parseInt(h);

				showModiHeightDialog(currHeight);
			}
		});
		imgHead = (ImageView) findViewById(R.id.img_head);
		imgHead.setOnClickListener(this);

		KJBitmap kjb = KJBitmap.create();
		String headUrl = PreferenceUtil.readString(this, C.sp.headurl);
		if (!TextUtils.isEmpty(headUrl)) {
			kjb.display(imgHead, HttpUtil.url_img + headUrl);
		}

		tvBirthday.setOnClickListener(this);
		tvSex.setOnClickListener(this);

		btnOk = (Button) findViewById(R.id.setting);
		btnOk.setOnClickListener(this);

		dialog = CustomProgressDialog.createDialog(this, false).setMessage(R.string.wating_set_info);

		editName.setText(PreferenceUtil.readString(this, C.sp.username, ""));
		String birthday = PreferenceUtil.readString(this, C.sp.birthday, "");
		tvBirthday.setTag("");
		if (birthday != null && !"".equals(birthday)) {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
			try {
				tvBirthday.setText(sdf1.format(sdf2.parse(birthday)));
				tvBirthday.setTag(birthday);
			} catch (ParseException e) {
				tvBirthday.setText("");
			}
		}

		boolean sex = PreferenceUtil.readBoolean(this, C.sp.sex);
		tvSex.setTag(sex ? "1" : "2");
		tvSex.setText(sex ? R.string.male : R.string.female);

		float weight = PreferenceUtil.readFloat(this, C.sp.weight);
		if (0 != weight) {
			editweight.setText("" + weight);
		}
		int height = PreferenceUtil.readInt(this, C.sp.height);
		if (0 != height) {
			editHeight.setText("" + height);
		}
	}

	@Override public void onClick(View view) {
		switch (view.getId()) {
		case R.id.edit_birthday:
			setBirthday();
			break;
		case R.id.edit_sex:
			showSexSelect();
			break;
		case R.id.setting:
			UserInfo userInfo = check();
			if (null != userInfo) {
				updateInfo(userInfo);
			}
			break;
		case R.id.img_head:
			showPhotoSelect();
			break;
		default:
			break;
		}
	}

	private int REQUEST_CODE_IMAGE_FORM_ALBUM = 1;
	private int REQUEST_CODE_IMAGE_FROM_CAMERA = 2;
	private String tempPhotoName = "temp.png";
	private int REQUEST_CODE_IMAGE_FROM_CROP = 3;

	private void showPhotoSelect() {
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("1", getString(R.string.album));
		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("2", getString(R.string.carmea));
		data.add(map1);
		data.add(map2);
		SelectDialog dialog = new SelectDialog(this, data, R.string.select_img, new OnItemClickListener() {

			@SuppressLint("SdCardPath") @Override public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
				if ("1".equals(view.getTag().toString())) {
					Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
					intent.setType("image/*");
					startActivityForResult(intent, REQUEST_CODE_IMAGE_FORM_ALBUM);
				}
				else {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/" + tempPhotoName)));
					startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CAMERA);
				}
			}
		});
		dialog.show();
	}

	@SuppressLint("SdCardPath") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CODE_IMAGE_FORM_ALBUM) {
				startPhotoZoom(data.getData());
			}
			else if (requestCode == REQUEST_CODE_IMAGE_FROM_CAMERA) {
				String photoPath = "/sdcard/" + tempPhotoName;
				File temp = new File(photoPath);
				startPhotoZoom(Uri.fromFile(temp));
			}
			else if (requestCode == REQUEST_CODE_IMAGE_FROM_CROP) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					Bitmap photo = extras.getParcelable("data");
					imgHead.setImageBitmap(photo);
					updateIcon(photo);
				}
			}
		}
	}

	private void updateIcon(final Bitmap photo) {
		final UserInfo info = new UserInfo();
		info.setPhone(PreferenceUtil.readString(App.i(), C.sp.phone));
		info.setPassword(PreferenceUtil.readString(App.i(), C.sp.password));
		final String url = HttpUtil.url + Base64Code.encode(C.request_msgid_post_user_icon.getBytes());
		new Thread() {
			public void run() {
				String result = UploadUtil.uploadFile("UserIcon.png", photo, url, info);
				if (!TextUtils.isEmpty(result)) {
					try {
						HeadImageResponse res = HttpUtil.gson.fromJson(result, HeadImageResponse.class);
						if (res.retcode == 0) {
							PreferenceUtil.write(UserInfoActivity.this, C.sp.headurl, res.userICONFileName);
						}
					} catch (JsonSyntaxException e) {
						runOnUiThread(new Runnable() {
							public void run() {
								showToast(R.string.upload_fail);
							}
						});
						e.printStackTrace();
					}
				}
				else {
					runOnUiThread(new Runnable() {
						public void run() {
							showToast(R.string.upload_fail);
						}
					});
					
				}
			};
		}.start();
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CROP);
	}

	private void updateInfo(UserInfo info) {
		info.msgid = C.request_msgid_post_user_change_info;
		dialog.show();

		// String userPhone = info.getPhone();
		// if(userPhone.length() == 11) {
		// // 修改用户信息加上86头
		// userPhone = C.app.china_phone + userPhone;
		// info.setPhone(userPhone);
		// }

		HttpUtil.requestJson(Method.POST, info, new ResponeListener() {

			@Override public void onResponse(BaseResponse response, String resultStr) {
				dialog.dismiss();
				updateResult(response.retcode);
			}

			@Override public void onErrorResponse(Exception error) {
				dialog.dismiss();
				showToast(SystemTool.checkNet(UserInfoActivity.this) ? R.string.request_error : R.string.net_error);
			}

		});
	}

	private void updateResult(int code) {
		if (code == 0) {
			showToast(R.string.update_info_success);
			PreferenceUtil.write(this, C.sp.username, editName.getText().toString().trim());
			boolean userSex = "\u7537".equals(tvSex.getText().toString().trim());
			PreferenceUtil.write(this, C.sp.sex, userSex);
			float userWeight = Float.parseFloat(editweight.getText().toString().trim());
			PreferenceUtil.write(this, C.sp.weight, userWeight);
			int userHeight = Integer.parseInt(editHeight.getText().toString().trim());
			PreferenceUtil.write(this, C.sp.height, userHeight);

			String birthday = tvBirthday.getText().toString().trim();
			Date bth = FormatUtil.parseDate(birthday, FormatUtil.yyyy_MM_dd);
			PreferenceUtil.write(this, C.sp.birthday, FormatUtil.formatDate(bth, FormatUtil.yyyyMMdd));
			int userAge = (int) ((System.currentTimeMillis() - bth.getTime()) / (365 * 24 * 3600000));
			PreferenceUtil.write(this, C.sp.user_age, userAge);

			finish();
		}
		else {
			showToast(R.string.update_info_error);
		}
	}

	@SuppressLint("SimpleDateFormat") private UserInfo check() {
		UserInfo userInfo = new UserInfo();

		Editable name = editName.getText();
		if (TextUtils.isEmpty(name)) {
			editName.setHint(R.string.name_null);
			return null;
		}
		else {
			if (name.toString().trim().length() > 10) {
				editName.setText("");
				editName.setHint(R.string.name_format);
				return null;
			}
			else {
				userInfo.setUsername(name.toString().trim());
			}
		}

		CharSequence birthday = tvBirthday.getText();
		if (TextUtils.isEmpty(birthday)) {
			tvBirthday.setHint(R.string.birthday_null);
			return null;
		}
		else {
			userInfo.setBirthday(tvBirthday.getTag().toString());
		}

		CharSequence sex = tvSex.getText();
		if (TextUtils.isEmpty(sex)) {
			tvSex.setHint(R.string.sex_null);
			return null;
		}
		else {
			userInfo.setSex(Integer.parseInt(tvSex.getTag().toString()));
		}

		String weight = editweight.getText().toString();
		if (TextUtils.isEmpty(weight)) {
			editweight.setHint(R.string.weight_null);
			return null;
		}
		else {
			userInfo.setWeight(Float.parseFloat(weight.toString()));
		}

		String height = editHeight.getText().toString();
		if (TextUtils.isEmpty(height)) {
			editHeight.setHint(R.string.height_null);
			return null;
		}
		else {
			userInfo.setHeight(Float.parseFloat(height.toString()));
		}
		userInfo.setPhone(PreferenceUtil.readString(this, C.sp.phone));
		userInfo.setPassword(PreferenceUtil.readString(this, C.sp.password));

		String servsion = "1.00"; // ring
		String hversion = "1.00"; // ring
		String appversion = SystemTool.getAppVersion(this);
		String phonedevice = "Android " + android.os.Build.BRAND + " " + android.os.Build.MODEL;
		String phoneversion = SystemTool.getSystemVersion();
		String ringid = RingBleService.sBleAdress == null ? "123456" : RingBleService.sBleAdress;
		userInfo.setSversion(servsion);
		userInfo.setHversion(hversion);
		userInfo.setAppversion(appversion);
		userInfo.setPhonedevice(phonedevice);
		userInfo.setPhoneversion(phoneversion);
		userInfo.setRingid(ringid);

		return userInfo;
	}

	public static final String DATEPICKER_TAG = "datepicker";

	public void setBirthday() {
		final Calendar calendar = Calendar.getInstance();

		DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), true);

		datePickerDialog.setVibrate(true);
		datePickerDialog.setYearRange(1985, 2028);
		datePickerDialog.setCloseOnSingleTapDay(false);
		datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG);
	}

	@Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
		String mon = (month + 1) < 10 ? "0" + (month + 1) : "" + (month + 1);
		String d = day < 10 ? "0" + day : day + "";
		String birthday = year + "-" + mon + "-" + d;
		tvBirthday.setText(birthday);
		tvBirthday.setTag(year + mon + d);
	}

	private void showSexSelect() {
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("1", getString(R.string.male));
		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("2", getString(R.string.female));
		data.add(map1);
		data.add(map2);
		final SelectDialog dialog = new SelectDialog(context, data, R.string.sex_select, new OnItemClickListener() {

			@Override public void onItemClick(AdapterView<?> arg0, View view, int poistion, long itemId) {
				if ("1".equals(view.getTag().toString())) {
					tvSex.setText(R.string.male);
					tvSex.setTag("1");
				}
				else {
					tvSex.setText(R.string.female);
					tvSex.setTag("2");
				}
			}
		});
		dialog.show();
	}

	/** WheelView 数据内容填充算法 */
	private String[] getWheelContent(int start, int num) {
		if (start < 0 || num < 0) {
			return null;
		}
		String[] content = new String[num];
		for (int i = start; i < content.length; i++) {
			if (start + num > 10) {
				content[i] = (i < 10 ? "0" : "") + String.valueOf(i);
			}
			else {
				content[i] = String.valueOf(i);
			}

		}
		return content;
	}

	/** 修改体重的对话框 */
	private Dialog dlgModiWeight;
	private final int MIN_WEIGHT = 20;
	private String weight1, weight2;

	private void showModiWeightDialog(float currWeight) {
		if (dlgModiWeight != null) {
			if (!dlgModiWeight.isShowing()) {
				dlgModiWeight.show();
			}
			return;
		}

		if (currWeight < MIN_WEIGHT) currWeight = 50;

		View content = LayoutInflater.from(this).inflate(R.layout.dialog_part_userinfo_settings, null);
		WheelView wheelWeight1 = (WheelView) content.findViewById(R.id.wheel_1);
		wheelWeight1.setOffset(2);
		wheelWeight1.setItems(Arrays.asList(getWheelContent(MIN_WEIGHT, 250)));
		wheelWeight1.setOnWheelViewListener(new OnWheelViewListener() {
			@Override public void onSelected(int selectedIndex, String item) {
				weight1 = item;
			}
		});
		WheelView wheelWeight2 = (WheelView) content.findViewById(R.id.wheel_2);
		wheelWeight2.setOffset(2);
		wheelWeight2.setItems(Arrays.asList(getWheelContent(0, 10)));
		wheelWeight2.setOnWheelViewListener(new OnWheelViewListener() {
			@Override public void onSelected(int selectedIndex, String item) {
				weight2 = item;
			}
		});
		weight1 = String.valueOf((int) currWeight);
		wheelWeight1.setSeletion((int) currWeight);
		weight2 = String.valueOf((int) (currWeight * 10) % 10);
		wheelWeight2.setSeletion((int) (currWeight * 10) % 10);

		dlgModiWeight = DialogUtil.init(this).create(content, true, true).setCancelListener(new View.OnClickListener() {
			@Override public void onClick(View v) {
				dlgModiWeight.dismiss();
			}
		}).setCancelText(R.string.confirm).setTitleText(R.string.set_weight_1).show();
		dlgModiWeight.setOnDismissListener(new OnDismissListener() {
			@Override public void onDismiss(DialogInterface dialog) {
				editweight.setText(weight1 + "." + weight2);
			}
		});
	}

	private Dialog dlgModiHeight;
	private String height;
	private final int MIN_HEIGHT = 50;

	/** 修改身高;单位厘米 */
	private void showModiHeightDialog(int currHeight) {
		if (dlgModiHeight != null) {
			if (!dlgModiHeight.isShowing()) {
				dlgModiHeight.show();
			}
			return;
		}

		if (currHeight < MIN_HEIGHT) currHeight = 150;

		View content = LayoutInflater.from(this).inflate(R.layout.dialog_part_userinfo_settings, null);
		WheelView wheelHeight1 = (WheelView) content.findViewById(R.id.wheel_1);
		wheelHeight1.setOffset(2);
		wheelHeight1.setItems(Arrays.asList(getWheelContent(MIN_HEIGHT, 250)));
		wheelHeight1.setOnWheelViewListener(new OnWheelViewListener() {
			@Override public void onSelected(int selectedIndex, String item) {
				height = item;
			}
		});

		height = String.valueOf((int) currHeight);
		wheelHeight1.setSeletion((int) currHeight);

		content.findViewById(R.id.lay_second_wheel).setVisibility(View.GONE);
		dlgModiHeight = DialogUtil.init(this).create(content, true, true).setCancelListener(new View.OnClickListener() {
			@Override public void onClick(View v) {
				dlgModiHeight.dismiss();
			}
		}).setCancelText(R.string.confirm).setTitleText(R.string.set_height_1).show();
		dlgModiHeight.setOnDismissListener(new OnDismissListener() {
			@Override public void onDismiss(DialogInterface dialog) {
				editHeight.setText(height);
			}
		});
	}

}
